package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.vo.ExchangeCodeVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author friday
 * @since 2024-01-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;

    @Async("generateExchangeCodeExecutor") //使用 generateExchangeCodeExecutor 自定义线程中的线程异步执行
    @Override
    public void asyncGenerateExchangeCode(Coupon coupon) {
        log.debug("生成兑换码  线程名：{}", Thread.currentThread().getName());
        Integer totalNum = coupon.getTotalNum(); //代表优惠券的总数量，也就是需要生成的兑换码的数量
        //方式1：循环兑换码总数量 循环中单个获取自增长id   incr
        //方式2：先调用 incrby 得到自增长id最大值，然后循环生成兑换码，可以不用每次循环调用redis了
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null){
            return;
        }
        int maxSerialNum = increment.intValue(); //自增id最大值
        int begin = maxSerialNum - totalNum + 1;

        //2.循环生成兑换码 调用工具类生成兑换码
        List<ExchangeCode> list = new ArrayList<>();
        for (int serialNum = begin; serialNum <= maxSerialNum ; serialNum++) {
            String code = CodeUtil.generateCode(serialNum, coupon.getId());//参数1：自增id；参数2：为优惠券id(内部会计算出0-的数字然后找对应的密钥（一共有16种密钥）)
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(serialNum); //兑换码id  ExchangeCode这个po类的主键生成策略需要修改为INPUT
            exchangeCode.setCode(code);
            exchangeCode.setExchangeTargetId(coupon.getId()); //优惠券id
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());//兑换码 兑换截止时间 就是优惠券领取的截止时间
            list.add(exchangeCode);
        }
        //3.将兑换码批量保存到db，exchange_code表 批量保存
        this.saveBatch(list);

        //4.写入redis缓存，member，couponId，score：兑换码的最大序列号 (本次生成兑换码 可省略)
        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY,coupon.getId().toString(), maxSerialNum);
    }

    //标记兑换码
    @Override
    public boolean updateExchangeCodeMark(long serialNum, boolean flag) {
        String key = PromotionConstants.COUPON_CODE_MAP_KEY;
        //修改兑换码 的 自增id  对应的offset 的值
        Boolean aBoolean = redisTemplate.opsForValue().setBit(key, serialNum, flag);
        return aBoolean!=null && aBoolean;
    }

    @Override
    public PageDTO<ExchangeCodeVO> queryCodePage(CodeQuery query) {
        // 1.分页查询兑换码
        Page<ExchangeCode> page = lambdaQuery()
                .eq(ExchangeCode::getStatus, query.getStatus())
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .page(query.toMpPage());
        // 2.返回数据
        return PageDTO.of(page, c -> new ExchangeCodeVO(c.getId(), c.getCode()));
    }
}
